package business;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.commons.lang3.StringUtils;

import utils.GeneralUtils;
import bean.ApplicationConfiguration;

public class Connection {

	private ApplicationConfiguration applicationConfiguration;

	private Socket socket;
	private BufferedReader reader;
	private PrintWriter writer;

	public Connection(ApplicationConfiguration applicationConfiguration) {
		this.applicationConfiguration = applicationConfiguration;
	}

	public void connect() {
		try {
			socket = new Socket(applicationConfiguration.getServer().getHost(),
					applicationConfiguration.getServer().getPort());

			writer = new PrintWriter(socket.getOutputStream(), true);

			reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		// send user profile data to the server
		prepareUserProfile();

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void disconnect() {
		writer.close();
		try {
			reader.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendText(String text) {
		if (StringUtils.isNotBlank(text)) {
			GeneralUtils.println(text);
			writer.println(text);
		}
	}

	public String receiveText() {
		if (socket.isConnected()) {
			try {
				return reader.readLine();
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		} else {
			return null;
		}
	}

	private void prepareUserProfile() {
		sendText(applicationConfiguration.getClientId());
		sendText("NICK "
				+ applicationConfiguration.getServer().getUserProfile()
						.getNickName());
	}

	public boolean isConnected() {
		return socket.isConnected();
	}

}
